package com.hoshing.test.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hoshing.test.entity.TUser;
import com.hoshing.test.service.ITUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 'imssmainjx.search_event_acount_hj' is not BASE TABLE 前端控制器
 * </p>
 *
 * @author hskj
 * @since 2021-12-09
 */
@RestController
@RequestMapping("/test/user")
public class TUserController{

    @Autowired
    ITUserService userService;

    @GetMapping("getAllUser")
    public String getAllUser(){
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        List<TUser> userList = userService.list(queryWrapper);
        return JSONObject.toJSONString(userList);
    }

    @GetMapping("getUser")
    public String getUser(@RequestParam("id") String id){
        //数据库为Varchar，代码为Long的时候，要用这种方式查询
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return JSONObject.toJSONString(userService.getOne(queryWrapper));
    }

    @GetMapping("addUser")
    public String addUser(@RequestParam("userName") String userName){
        TUser user = new TUser();
        user.setName(userName);
        userService.save(user);
        return "添加成功";
    }

    /**
     * 1.数据库选择必须是配置文件声明过的
     * 2.虽然单表可以跨库查询出来，但是关联查询无法跨库，所以垂直水平分库分表的时候必须考虑清楚
     * 3.xml文件里的sql语句，shardingsphere也可以根据配置文件动态构造语句
     * 4.支持跨库、跨表 order by 等操作（可能是把查询出来的数据放在虚拟库这样的介质中再操作）
     */
    @GetMapping("getAllUserInfo")
    public String getAllUserInfo(){
        List<Map<String, Object>> datas = userService.getAllUserInfo();
        StringBuilder sb = new StringBuilder();
        datas.forEach(data -> {
            sb.append(JSONObject.toJSONString(data));
            sb.append("</br>");
        });
        return sb.toString();
    }
}

